package ce51.dunghn.imagethread;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;

import vg.com.chatonline.activity.R;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import ce51.dunghn.chatslide.LeftAndRightActivity;
import ce51.dunghn.imagethread.Constants.Extra;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.ImageDownloader;
import com.nostra13.universalimageloader.core.download.URLConnectionImageDownloader;
import com.nostra13.universalimageloader.utils.FileUtils;
import com.vg.view.info_User;

public class ImagePagerActivity extends BaseActivity {

	DisplayImageOptions options;
	String[] imageUrls;
	int pagerPosition;
	ViewPager pager;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_image_pager);

		Bundle bundle = getIntent().getExtras();
		imageUrls = bundle.getStringArray(Extra.IMAGES);
		pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);

		options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.image_for_empty_url)
				.resetViewBeforeLoading().cacheOnDisc()
				.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
				.bitmapConfig(Bitmap.Config.RGB_565)
				.displayer(new FadeInBitmapDisplayer(300)).build();

		pager = (ViewPager) findViewById(R.id.pager);
		pager.setAdapter(new ImagePagerAdapter(imageUrls));
		pager.setCurrentItem(pagerPosition);

	}

	// Tao menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, 0, Menu.NONE, "Xem thông tin");
		menu.add(Menu.NONE, 1, Menu.NONE, "Nhắn tin");
		menu.add(Menu.NONE, 2, Menu.NONE, "Tải về");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			Intent i1 = new Intent(getApplicationContext(), info_User.class);
			startActivity(i1);
			return true;
		case 1:
			Intent i2 = new Intent(getApplicationContext(),
					LeftAndRightActivity.class);
			startActivity(i2);
			return true;
		case 2:
			// Tao folder moi de luu anh
			String path = Environment.getExternalStorageDirectory().toString();
			File file = new File(path + "/chatvg/");
			if (!file.exists()) {
				new File(path + "/chatvg/").mkdir();
			}
			
			File imgName = new File(path + "/chatvg/"
					+ getImageName(imageUrls[pager.getCurrentItem()]));
			InputStream sourceStream;
			File cachedImage = ImageLoader.getInstance().getDiscCache()
					.get(imageUrls[pager.getCurrentItem()]);
			try {
				if (cachedImage.exists()) {
					sourceStream = new FileInputStream(cachedImage);
				} else {
					ImageDownloader downloader = new URLConnectionImageDownloader();
					sourceStream = downloader.getStream(new URI(imageUrls[pager
							.getCurrentItem()]));
				}

				OutputStream targetStream = new FileOutputStream(imgName);
				FileUtils.copyStream(sourceStream, targetStream);
				targetStream.close();
				sourceStream.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (URISyntaxException e) {
				e.printStackTrace();
			}
			Toast.makeText(getBaseContext(),
					getImageName(imageUrls[pager.getCurrentItem()]),
					Toast.LENGTH_LONG).show();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	// Lay ten cua anh tu url
	public String getImageName(String url) {
		String imgName = "";
		String token[] = new String[url.split("/").length];
		token = url.split("/");
		imgName = token[token.length - 1];
		return imgName;
	}

	// Adapter cho Pagerview
	private class ImagePagerAdapter extends PagerAdapter {

		private String[] images;
		private LayoutInflater inflater;

		ImagePagerAdapter(String[] images) {
			this.images = images;
			inflater = getLayoutInflater();
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
		}

		@Override
		public void finishUpdate(View container) {
		}

		@Override
		public int getCount() {
			return images.length;
		}

		@Override
		public Object instantiateItem(View view, int position) {
			final View imageLayout = inflater.inflate(
					R.layout.item_pager_image, null);
			final ImageView imageView = (ImageView) imageLayout
					.findViewById(R.id.image);
			final ProgressBar spinner = (ProgressBar) imageLayout
					.findViewById(R.id.loading);

			imageLoader.displayImage(images[position], imageView, options,
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingStarted() {
							spinner.setVisibility(View.VISIBLE);
						}

						@Override
						public void onLoadingFailed(FailReason failReason) {
							String message = null;
							switch (failReason) {
							case IO_ERROR:
								message = "Input/Output error";
								break;
							case OUT_OF_MEMORY:
								message = "Out Of Memory error";
								break;
							case UNKNOWN:
								message = "Unknown error";
								break;
							}
							Toast.makeText(ImagePagerActivity.this, message,
									Toast.LENGTH_SHORT).show();

							spinner.setVisibility(View.GONE);
							imageView
									.setImageResource(android.R.drawable.ic_delete);
						}

						@Override
						public void onLoadingComplete(Bitmap loadedImage) {
							spinner.setVisibility(View.GONE);
						}
					});

			((ViewPager) view).addView(imageLayout, 0);
			return imageLayout;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view.equals(object);
		}

		@Override
		public void restoreState(Parcelable state, ClassLoader loader) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View container) {
		}
	}
}